package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import com.zzyl.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.service.IContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.function.Consumer;

/**
 * 合同Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService
{
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询合同
     * 
     * @param id 合同主键
     * @return 合同
     */
    @Override
    public Contract selectContractById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询合同列表
     * 
     * @param contract 合同
     * @return 合同
     */
    @Override
    public List<Contract> selectContractList(Contract contract)
    {
        return contractMapper.selectContractList(contract);
    }

    /**
     * 新增合同
     * 
     * @param contract 合同
     * @return 结果
     */
    @Override
    public int insertContract(Contract contract)
    {
        return save(contract) ? 1 : 0;
    }

    /**
     * 修改合同
     * 
     * @param contract 合同
     * @return 结果
     */
    @Override
    public int updateContract(Contract contract)
    {
        return updateById(contract) ? 1 : 0;
    }

    /**
     * 批量删除合同
     * 
     * @param ids 需要删除的合同主键
     * @return 结果
     */
    @Override
    public int deleteContractByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除合同信息
     * 
     * @param id 合同主键
     * @return 结果
     */
    @Override
    public int deleteContractById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void updateContractStatus() {
        List<Contract> list = this.list();
        //判断合同表是否为空，为空则直接返回
        if (CollectionUtils.isEmpty( list)){
            return;
        }

        list.forEach(new Consumer<Contract>() {
            @Override
            public void accept(Contract contract) {
                LocalDateTime now = LocalDateTime.now();
                if (now.isBefore(contract.getStartDate())){
                    contract.setStatus(0);
                } else if (now.isAfter(contract.getStartDate()) && now.isBefore(contract.getEndDate())){
                    contract.setStatus(1);
                } else if (now.isAfter(contract.getEndDate())){
                    contract.setStatus(2);
                }
            }
        });

        this.updateBatchById(list);
    }
}
